
package org.icnmasjid.member.dao.hibernate;

import java.util.List;

import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.icnmasjid.member.dao.hibernate.BaseDaoHibernate;
import org.icnmasjid.member.model.Login;
import org.icnmasjid.member.dao.LoginDao;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ObjectRetrievalFailureException;

public class LoginDaoHibernate extends BaseDaoHibernate implements LoginDao, UserDetailsService {

    /**
     * @see org.icnmasjid.member.dao.LoginDao#getLogins(org.icnmasjid.member.model.Login)
     */
    public List getLogins(final Login login) {
        return getHibernateTemplate().findByExample(login);
    }

    /**
     * @see org.icnmasjid.member.dao.LoginDao#getLogin(Integer id)
     */
    public Login getLogin(final Integer id) {
        Login login = (Login) getHibernateTemplate().get(Login.class, id);
        if (login == null) {
            log.warn("uh oh, login with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Login.class, id);
        }

        return login;
    }

    /**
     * @see org.icnmasjid.member.dao.LoginDao#saveLogin(Login login)
     */
    public void saveLogin(final Login login) {
        getHibernateTemplate().saveOrUpdate(login);
    }

    /**
     * @see org.icnmasjid.member.dao.LoginDao#removeLogin(Integer id)
     */
    public void removeLogin(final Integer id) {
        getHibernateTemplate().delete(getLogin(id));
    }

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        List users = getHibernateTemplate().find("from Login where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
	}
}
